<template>
  <div class="progress-container" @click="hidePopup">
    <div class="node-container">
      <div
        class="progress-item"
        v-for="(item, index) in sortedProgress"
        :key="item.id"
      >
        <div class="node-text" :class="{ hightlight: item.status }">
          {{ item.name }}
        </div>

        <!-- 圆点 -->
        <div
          class="node-dot"
          :class="{ finish: item.status }"
          @click.stop="showPopup(item, index)"
        ></div>

        <!-- 提示框 -->
        <div class="tool-tip">{{ '完成时间:' + item.date }}</div>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <div v-if="popupVisible" class="popup" @click.stop>
      <div class="popup-content">
        <div class="form-item">
          <label><strong>名称：</strong></label>
          <input type="text" v-model="editableItem.name" />
        </div>
        <div class="form-item">
          <label><strong>日期：</strong></label>
          <input type="text" v-model="editableItem.date" placeholder="YYYY/MM/DD" />
        </div>
        <div class="form-item">
          <label><strong>状态：</strong></label>
          <picker
            mode="selector"
            :range="['已完成','未完成']"
            :value="editableItem.status ? 0 : 1"
            @change="onStatusChange"
          ></picker>
        </div>
        <div class="form-item">
          <label><strong>描述：</strong></label>
          <textarea v-model="editableItem.describe"></textarea>
        </div>

        <div class="popup-actions">
          <button @click="hidePopup">关闭</button>
          <button @click="saveItem">保存</button>
        </div>
      </div>
    </div>

    <div class="progress-line">
      <div class="line-bg"></div>
      <div class="line-top"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const progress = ref([])
const popupVisible = ref(false)
const selectedIndex = ref(null)
const editableItem = ref({})

// 根据日期排序
const sortedProgress = computed(() => {
  return [...progress.value].sort((a, b) => {
    const [y1, m1, d1] = a.date.split('/').map(Number)
    const [y2, m2, d2] = b.date.split('/').map(Number)
    if (y1 !== y2) return y1 - y2
    if (m1 !== m2) return m1 - m2
    return d1 - d2
  })
})

function showPopup(item, index) {
  selectedIndex.value = index
  popupVisible.value = true
  editableItem.value = { ...item }
}

function hidePopup() {
  popupVisible.value = false
}

// 小程序 picker 状态改变
function onStatusChange(e) {
  const index = e.detail.value
  editableItem.value.status = index === 0 // 0 => 已完成 true
}

// 保存更新到后端
async function saveItem() {
  const userInfo = uni.getStorageSync('userInfo')
  if (!userInfo?.username || !userInfo?.password) {
    uni.showToast({ title: '未找到用户信息', icon: 'none' })
    return
  }

  const payload = {
    username: userInfo.username,
    password: userInfo.password,
    progressItem: {
      id: editableItem.value.id || selectedIndex.value.toString(),
      name: editableItem.value.name,
      date: editableItem.value.date,
      sate: editableItem.value.status ? 'true' : 'false',
      describe: editableItem.value.describe
    }
  }

  try {
    const res = await uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/update_Progressline',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: payload
    })

    if (res.data.success) {
      uni.showToast({ title: '保存成功', icon: 'success' })
      // 更新原数组
      progress.value[selectedIndex.value] = { ...editableItem.value }
      hidePopup()
    } else {
      uni.showToast({ title: res.data.message || '保存失败', icon: 'none' })
    }
  } catch (err) {
    console.error(err)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }
}

// 获取进度条列表
async function getProgressLineList() {
  const userInfo = uni.getStorageSync('userInfo')
  if (!userInfo?.username || !userInfo?.password) return

  try {
    const res = await uni.request({
      url: 'https://xrqr0h0x1w.gzg.sealos.run/get_progressLineListByUserName',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: {
        username: userInfo.username,
        password: userInfo.password
      }
    })

    if (res.data.code === 0) {
      progress.value = res.data.data.map((item, index) => ({
        id: index.toString(),
        name: item.name,
        date: item.date,
        status: item.sate === 'true',
        describe: item.describe || ''
      }))
    } else {
      uni.showToast({ title: res.data.msg || '获取进度失败', icon: 'none' })
    }
  } catch (err) {
    console.error(err)
    uni.showToast({ title: '网络错误', icon: 'none' })
  }
}

getProgressLineList()
</script>

<style scoped>
.progress-container { position: relative; width: 100%; height: 80px; }
.node-container { display: flex; }
.progress-item { position: relative; width: 100px; height: 55px; }
.progress-item:hover .tool-tip { visibility: visible; }

/* 节点文字 */
.node-text {
  width: 100%;
  text-align: center;
  font-size: 16px;
  color: #93b3cf; /* 默认灰色 */
  position: absolute;
  bottom: 10px;
  left: 0;
}
.hightlight {
  color: #53ff9e; /* 当前日期早于节点显示绿色 */
}

/* 小圆点统一淡粉色 */
.node-dot {
  position: absolute;
  top: 47px;
  left: 47px;
  width: 10px;
  height: 10px;
  z-index: 2;
  border-radius: 50%;
  background-color: #f8c6d6; /* 淡粉色 */
  cursor: pointer;
}

/* 提示框 */
.tool-tip {
  visibility: hidden;
  position: absolute;
  top: 56px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #0b1624;
  color: #fff;
  font-size: 14px;
  padding: 12px;
  z-index: 3;
  border-radius: 3px;
  white-space: nowrap;
  line-height: 30px;
}

/* 进度条统一淡粉色 */
.progress-line { width: 400px; }
.line-bg, .line-top {
  position: absolute;
  top: 50px;
  left: 0;
  height: 4px;
  border-radius: 2px;
  background-color: #f8c6d6; /* 淡粉色 */
}
.line-bg { width: 100%; }
.line-top { width: 50%; } /* 可动态调整长度 */

/* 弹窗 */
.popup { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; justify-content: center; align-items: center; }
.popup-content { background: #fff; border-radius: 8px; padding: 20px; width: 280px; }
.form-item { margin: 10px 0; text-align: left; }
.form-item input, .form-item textarea { width: 100%; margin-top: 5px; box-sizing: border-box; }
.form-item textarea { height: 60px; }
.popup-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 10px; }
.popup-actions button { padding: 5px 12px; border: none; border-radius: 4px; background-color: #409eff; color: #fff; cursor: pointer; }
</style>
